using Microsoft.EntityFrameworkCore;
using OrderingSystem.Core.Entities;
using OrderingSystem.Core.Interfaces;
using OrderingSystem.Infrastructure.Data;

namespace OrderingSystem.Infrastructure.Services
{
    public class ConfigService : IConfigService
    {
        private readonly ApplicationDbContext _context;

        public ConfigService(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IEnumerable<Config>> GetConfigsAsync()
        {
            return await _context.Configs.ToListAsync();
        }

        public async Task<Config> GetConfigByNameAsync(string name)
        {
            return await _context.Configs.FirstOrDefaultAsync(c => c.name == name);
        }

        public async Task<Config> GetConfigAsync(long id)
        {
            return await _context.Configs.FindAsync(id);
        }

        public async Task<Config> CreateConfigAsync(Config config)
        {
            _context.Configs.Add(config);
            await _context.SaveChangesAsync();
            return config;
        }

        public async Task<Config> UpdateConfigAsync(Config config)
        {
            var existingConfig = await _context.Configs.FindAsync(config.id);
            if (existingConfig == null)
            {
                return null;
            }

            existingConfig.name = config.name;
            existingConfig.value = config.value;

            await _context.SaveChangesAsync();
            return existingConfig;
        }

        public async Task DeleteConfigAsync(long id)
        {
            var config = await _context.Configs.FindAsync(id);
            if (config != null)
            {
                _context.Configs.Remove(config);
                await _context.SaveChangesAsync();
            }
        }

        public async Task<(IEnumerable<Config> Items, int Total)> GetConfigsPageAsync(int page, int limit, string sort = "id", string order = "desc")
        {
            var query = _context.Configs.AsQueryable();

            // 排序
            if (order.ToLower() == "asc")
            {
                query = sort.ToLower() switch
                {
                    "name" => query.OrderBy(c => c.name),
                    _ => query.OrderBy(c => c.id)
                };
            }
            else
            {
                query = sort.ToLower() switch
                {
                    "name" => query.OrderByDescending(c => c.name),
                    _ => query.OrderByDescending(c => c.id)
                };
            }

            var total = await query.CountAsync();
            var items = await query
                .Skip((page - 1) * limit)
                .Take(limit)
                .Select(c => new Config
                {
                    id = c.id,
                    name = c.name,
                    value = c.value
                })
                .ToListAsync();

            return (items, total);
        }
    }
} 